<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
*/

/**
* Responses Controller
*
* This controller performs browse actions.
*
* The browse() action is responsible for rendering the response view, which loads the JQGrid table.
* ...The grid in turns issues a JSON POST request to the getResponses_json() action.
* ...
* ...It is important that the order of fields generated by both actions match.
* ...For the browse() action, the $column_model is built up for each column in the table. The grid
* ...uses the column model to render column headings and search bar.
* ...The getResponses_json() action populated the $aSurveyEntry array with the values that must be
* ...populated for each row and column of the table.
*
*
*
* @package        LimeSurvey
* @subpackage    Backend
*/
class responses extends Survey_Common_Action
{

    /**
    * @var string : Default layout is bare : temporary to real layout
    */
    public $layout = 'bare';

    function __construct($controller, $id)
    {
        parent::__construct($controller, $id);

        Yii::app()->loadHelper('surveytranslator');
    }

    private function _getData($params)
    {
        if (is_numeric($params))
        {
            $iSurveyId = $params;
        }
        elseif (is_array($params))
        {
            extract($params);
        }
        $aData = array();
        // Set the variables in an array
        $aData['surveyid'] = $aData['iSurveyId'] = (int) $iSurveyId;
        if (!empty($iId))
        {
            $aData['iId'] = (int) $iId;
        }
        $aData['imageurl'] = Yii::app()->getConfig('imageurl');
        $aData['action'] = Yii::app()->request->getParam('action');
        $aData['all']=Yii::app()->request->getParam('all');
        $thissurvey=getSurveyInfo($iSurveyId);
        if(!$thissurvey)// Already done in Survey_Common_Action
        {
            Yii::app()->session['flashmessage'] = gT("Invalid survey ID");
            $this->getController()->redirect(array("admin/index"));
        }
        elseif($thissurvey['active'] != 'Y')
        {
            Yii::app()->session['flashmessage'] = gT("This survey has not been activated. There are no results to browse.");
            $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
        }

        //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.

        $aData['surveyinfo'] = $thissurvey;

        if (Yii::app()->request->getParam('browselang'))
        {
            $aData['language'] = Yii::app()->request->getParam('browselang');
            $aData['languagelist'] = $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
            $aData['languagelist'][] = Survey::model()->findByPk($iSurveyId)->language;
            if (!in_array($aData['language'], $languagelist))
            {
                $aData['language'] = $thissurvey['language'];
            }
        }
        else
        {
            $aData['language'] = $thissurvey['language'];
        }

        $aData['qulanguage'] = Survey::model()->findByPk($iSurveyId)->language;

        $aData['surveyoptions'] = '';
        $aData['browseoutput']  = '';

        return $aData;
    }

    public function view($iSurveyID, $iId, $sBrowseLang = '')
    {
        if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
        {
            $aData = $this->_getData(array('iId' => $iId, 'iSurveyId' => $iSurveyID, 'browselang' => $sBrowseLang));
            $sBrowseLanguage = $aData['language'];

            extract($aData);

            $aViewUrls = array();

            $fncount = 0;
            $fieldmap = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);

            //add token to top of list if survey is not private
            if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
            {
                $fnames[] = array("token", gT("Token ID"), 'code'=>'token');
                $fnames[] = array("firstname", gT("First name"), 'code'=>'firstname');// or token:firstname ?
                $fnames[] = array("lastname", gT("Last name"), 'code'=>'lastname');
                $fnames[] = array("email", gT("Email"), 'code'=>'email');
            }
            $fnames[] = array("submitdate", gT("Submission date"), gT("Completed"), "0", 'D','code'=>'submitdate');
            $fnames[] = array("completed", gT("Completed"), "0");

            foreach ($fieldmap as $field)
            {
                if ($field['fieldname'] == 'lastpage' || $field['fieldname'] == 'submitdate')
                    continue;
                if ($field['type'] == 'interview_time')
                    continue;
                if ($field['type'] == 'page_time')
                    continue;
                if ($field['type'] == 'answer_time')
                    continue;

                //$question = $field['question'];
                $question = viewHelper::getFieldText($field);

                if ($field['type'] != "|")
                {
                    $fnames[] = array($field['fieldname'], viewHelper::getFieldText($field),'code'=>viewHelper::getFieldCode($field,array('LEMcompat'=>true)));
                }
                elseif ($field['aid'] !== 'filecount')
                {
                    $qidattributes = getQuestionAttributeValues($field['qid']);

                    for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
                    {
                        $filenum=sprintf(gT("File %s"),$i + 1);
                        if ($qidattributes['show_title'] == 1)
                            $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('Title').")",'code'=>viewHelper::getFieldCode($field).'(title)', "type" => "|", "metadata" => "title", "index" => $i);

                        if ($qidattributes['show_comment'] == 1)
                            $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('Comment').")",'code'=>viewHelper::getFieldCode($field).'(comment)', "type" => "|", "metadata" => "comment", "index" => $i);

                        $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('File name').")",'code'=>viewHelper::getFieldCode($field).'(name)', "type" => "|", "metadata" => "name", "index" => $i);
                        $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".gT('File size').")",'code'=>viewHelper::getFieldCode($field).'(size)', "type" => "|", "metadata" => "size", "index" => $i);

                        //$fnames[] = array($field['fieldname'], "File ".($i+1)." - ".$field['question']." (extension)", "type"=>"|", "metadata"=>"ext",     "index"=>$i);
                    }
                }
                else
                {
                    $fnames[] = array($field['fieldname'], gT("File count"));
                }
            }

            $nfncount = count($fnames) - 1;
            if ($iId < 1)
            {
                $iId = 1;
            }

            $exist = SurveyDynamic::model($iSurveyID)->exist($iId);
            $next = SurveyDynamic::model($iSurveyID)->next($iId,true);
            $previous = SurveyDynamic::model($iSurveyID)->previous($iId,true);
            $aData['exist'] = $exist;
            $aData['next'] = $next;
            $aData['previous'] = $previous;
            $aData['id'] = $iId;

            $aViewUrls[] = 'browseidheader_view';
            if($exist)
            {
                $oPurifier=new CHtmlPurifier();
                //SHOW INDIVIDUAL RECORD
                $oCriteria = new CDbCriteria();
                if ($aData['surveyinfo']['anonymized'] == 'N' && tableExists("{{tokens_$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
                {
                    $oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
                }

                $oCriteria->addCondition("id = {$iId}");
                $iIdresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
                foreach ($iIdresult as $iIdrow)
                {
                    $iId = $iIdrow['id'];
                    $rlanguage = $iIdrow['startlanguage'];
                }
                $next = SurveyDynamic::model($iSurveyID)->next($iId);
                $previous = SurveyDynamic::model($iSurveyID)->previous($iId);
                $aData['bHasFile']=false;
                if (isset($rlanguage))
                {
                    $aData['rlanguage'] = $rlanguage;
                }
                foreach ($iIdresult as $iIdrow)
                {
                    $highlight = false;
                    for ($i = 0; $i < $nfncount + 1; $i++)
                    {
                        if ($fnames[$i][0] != 'completed' && is_null($iIdrow[$fnames[$i][0]]))
                        {
                            continue;   // irrelevant, so don't show
                        }
                        $inserthighlight = '';
                        if ($highlight)
                            $inserthighlight = "class='highlight'";

                        if ($fnames[$i][0] == 'completed')
                        {
                            if ($iIdrow['submitdate'] == NULL || $iIdrow['submitdate'] == "N")
                            {
                                $answervalue = "N";
                            }
                            else
                            {
                                $answervalue = "Y";
                            }
                        }
                        else
                        {
                            if (isset($fnames[$i]['type']) && $fnames[$i]['type'] == "|")
                            {
                                $index = $fnames[$i]['index'];
                                $metadata = $fnames[$i]['metadata'];
                                $phparray = json_decode_ls($iIdrow[$fnames[$i][0]]);

                                if (isset($phparray[$index]))
                                {
                                    switch ($metadata)
                                    {
                                        case "size":
                                            $answervalue = sprintf(gt("%s KB"),intval($phparray[$index][$metadata]));
                                            break;
                                        case "name":
                                            $answervalue = CHtml::link(
                                                $oPurifier->purify(rawurldecode($phparray[$index][$metadata])),
                                                $this->getController()->createUrl("/admin/responses",array("sa"=>"actionDownloadfile","surveyid"=>$surveyid,"iResponseId"=>$iId,"sFileName"=>$phparray[$index][$metadata]))
                                            );
                                            break;
                                        default:
                                            $answervalue = htmlspecialchars(strip_tags(stripJavaScript($phparray[$index][$metadata])));
                                    }
                                    $aData['bHasFile']=true;
                                }
                                else
                                    $answervalue = "";
                            }
                            else
                            {
                                $answervalue = htmlspecialchars(strip_tags(stripJavaScript(getExtendedAnswer($iSurveyID, $fnames[$i][0], $iIdrow[$fnames[$i][0]], $sBrowseLanguage))), ENT_QUOTES);
                            }
                        }
                        $aData['answervalue'] = $answervalue;
                        $aData['inserthighlight'] = $inserthighlight;
                        $aData['fnames'] = $fnames;
                        $aData['i'] = $i;
                        $aViewUrls['browseidrow_view'][] = $aData;
                    }
                }
            }
            else
            {
                Yii::app()->session['flashmessage'] = gT("This response ID is invalid.");
            }

            $aViewUrls[] = 'browseidfooter_view';

            $this->_renderWrappedTemplate('',$aViewUrls, $aData);
        }
        else
        {
            $aData['surveyid'] = $iSurveyID;
            App()->getClientScript()->registerPackage('jquery-superfish');
            $message['title']= gT('Access denied!');
            $message['message']= gT('You do not have sufficient rights to access this page.');
            $message['class']= "error";
            $this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
        }
    }

    public function index($iSurveyID)
    {
        $aData = $this->_getData($iSurveyID);
        extract($aData);
        $aViewUrls = array();
        $sBrowseLanguage = $aData['language'];

        /**
        * fnames is used as informational array
        * it containts
        *             $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
        */
        if (Yii::app()->request->getPost('sql'))
        {
            $aViewUrls[] = 'browseallfiltered_view';
        }

        $aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
        $aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
        if (tableExists('{{tokens_' . $iSurveyID . '}}') && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
        {
            $aData['with_token']= Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}');
            $aData['tokeninfo'] = Token::model($iSurveyID)->summary();
        }

        $aViewUrls[] = 'browseindex_view';
        $this->_renderWrappedTemplate('',$aViewUrls, $aData);
    }



    function browse($iSurveyId)
    {

        if(!Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
        {
            $aData['surveyid'] = $iSurveyId;
            $message['title']= gT('Access denied!');
            $message['message']= gT('You do not have sufficient rights to access this page.');
            $message['class']= "error";
            $this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
            Yii::app()->end();
        }
        App()->getClientScript()->registerPackage('jqgrid');
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "listresponse.js");

        $aData = $this->_getData($iSurveyId);
        extract($aData);
        $aViewUrls = array();
        $sBrowseLanguage = $aData['language'];
        // Some specific column
        $aSpecificColumns=array(
            'submitdate', // Replaced by completed : TODO : add it if is a real date
            'token', // Replaced by tokens.token
            'id', // Allways adding it at start
            'lastpage', // After id, before completed
        );
        // The column model must be built dynamically, since the columns will differ from survey to survey, depending on the questions.
        $column_model = array();
        // The first few colums are fixed.
        $column_model[] = array(
            'name' => 'actions',
            'index'=> 'actions',
            'sorttype' => 'string',
            'sortable' => false,
            'width' => '100',
            'resizable' => true,
            'align' => 'left',
            'label' => gt("Actions"),
            'search' => false,
            'hidedlg'=>true,
        );
        $fields = createFieldMap($iSurveyId,'full', true, false, $aData['language']);
        // Specific columns at start
        $column_model[] = array(
            'name'=>'id',
            'index'=>'id',
            'sorttype'=>'integer',
            'sortable'=>true,
            'width'=>'100',
            'resizable' => true,
            'align'=>'center',
            'title'=>viewHelper::getFieldText($fields['id']),
            'hidedlg'=>true,
        );
        $column_model[] = array(
            'name'=>'lastpage',
            'index'=>'lastpage',
            'sorttype'=>'integer',
            'sortable'=>true,
            'width'=>'100',
            'resizable' => true,// Strangely : don't work
            'align'=>'center',
            'title'=>viewHelper::getFieldText($fields['lastpage']),
        );
        $bHidden=false;
        if (isset($_SESSION['survey_'.$iSurveyId]['HiddenFields']))
        {
            $bHidden=in_array('completed',$_SESSION['survey_'.$iSurveyId]['HiddenFields']);
        }
        $column_model[] = array(
            'name' => 'completed',
            'index'=>'completed',
            'sorttype'=>'string',
            'stype'=>'select',
            'editoptions'=>array(
                'value'=>array(
                    ""=>gt("All"),
                    "Y"=>gt("Yes"),
                    "N"=>gt("No"),
                ),
            ),

            'sortable'=>true,
            'hidden'=>$bHidden,
            'width'=>'100',
            'align'=>'center',
            'label' => gt("Completed"),
        );

        //add token to top of list if survey is not private
        if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyId)) //add token to top of list if survey is not private
        {
            $column_model[] = array(
                'name'=>'token',
                'index'=>'token',
                'sorttype'=>'string',
                'sortable'=>true, 'width'=>'100',
                'align'=>'left',
                'title'=>gt('Token')
            );
            $column_model[] = array(
                'name'=>'firstname',
                'index'=>'firstname',
                'sorttype'=>'string',
                'sortable'=>true,
                'width'=>'100',
                'align'=>'left',
                'title'=>gt('First name'),
            );
            $column_model[] = array(
                'name'=>'lastname',
                'index'=>'lastname',
                'sorttype'=>'string',
                'sortable'=>true,
                'width'=>'100',
                'align'=>'left',
                'title'=>gt('Last Name'),
            );
            $column_model[] = array(
                'name'=>'email',
                'index'=>'email',
                'sorttype'=>'string',
                'sortable'=>true,
                'width'=>'100',
                'align'=>'left',
                'title'=>gt('Email'),
            );
        }


        // All other columns are based on the questions.
        // An array to control unicity of $code (EM code)
        $aCodes=array();
        foreach ($fields as $fielddetails)
        {
            if(in_array($fielddetails['fieldname'],$aSpecificColumns))
                continue;

            // no headers for time data
            if ($fielddetails['type'] == 'interview_time')
                continue;
            if ($fielddetails['type'] == 'page_time')
                continue;
            if ($fielddetails['type'] == 'answer_time')
                continue;



            $question = $fielddetails['question'];
            if ($fielddetails['type'] == "|")
            {
                $fnames=array();
                $code=viewHelper::getFieldCode($fielddetails,array('LEMcompat'=>true));// This must be unique ......

                if ($fielddetails['aid'] !== 'filecount')
                {
                    $qidattributes = getQuestionAttributeValues($fielddetails['qid']);

                    for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
                    {
                        if ($qidattributes['show_title'] == 1)
                            $fnames[] = array($code.'_'.$i.'_title', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(Title)", "type" => "|", "metadata" => "title", "index" => $i);

                        if ($qidattributes['show_comment'] == 1)
                            $fnames[] = array($code.'_'.$i.'_comment', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(Comment)", "type" => "|", "metadata" => "comment", "index" => $i);

                        $fnames[] = array($code.'_'.$i.'_name', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(File name)", "type" => "|", "metadata" => "name", "index" => $i);
                        $fnames[] = array($code.'_'.$i.'_size', "File " . ($i + 1) . " - " . $fielddetails['question'] . "(File size)", "type" => "|", "metadata" => "size", "index" => $i);
                    }
                }
                else
                    $fnames[] = array($code.'_count', "File count");
                $bHidden=false;
                if (isset($_SESSION['survey_'.$iSurveyId]['HiddenFields']))
                {
                    $bHidden=in_array($fielddetails['fieldname'],$_SESSION['survey_'.$iSurveyId]['HiddenFields']);
                }
                foreach ($fnames as $aFileInfoField)
                {
                    $column_model[] = array(
                        'name' => $aFileInfoField[0],
                        'index' => $aFileInfoField[0],
                        'sortable' => false,
                        'width' => '100',
                        'align' => 'left',
                        'editable' => false,
                        'search' => false,
                        'hidden' => $bHidden,
                        'title' => $aFileInfoField[1],
                    );
                }
                continue;

            }

            // TODO: upload question type have more than one column (see before)
            // Construction of clean name and title
            $code=viewHelper::getFieldCode($fielddetails,array('LEMcompat'=>true));// This must be unique ......
            //fix unicity of $code
            if(isset($aCodes[$code]))
            {
                $aCodes[$code]++;
                $code="{$code}-{$aCodes[$code]}";
            }
            else
            {
                $aCodes[$code]=0;
            }
            $text=viewHelper::getFieldText($fielddetails);
            $textabb=viewHelper::getFieldText($fielddetails,array('abbreviated'=>10));
            $bHidden=false;
            if (isset($_SESSION['survey_'.$iSurveyId]['HiddenFields']))
            {
                $bHidden=in_array($fielddetails['fieldname'],$_SESSION['survey_'.$iSurveyId]['HiddenFields']);
            }
            $column_model[] = array(
                'name' => $code,
                'index' => $fielddetails['fieldname'],
                'sorttype' => 'string',// Depend of question type can be excellent
                'sortable' => true,
                'width' => '100',
                'align' => 'left',
                'editable' => false,
                'hidden' => (bool)$bHidden,
                'title' => $text,
            );
            
        }

        $column_model_txt = ls_json_encode($column_model);
        $column_names = array();
        foreach ($column_model as $column)
        {
            if(isset($column['title']))
                $column_names[] = "<strong class='qcode'>{$column['name']}</strong> <span class='separator hidden'>:</span> <span class='questiontext'>".ellipsize($column['title'],30,0.6,"...")."</span>";
            elseif(isset($column['label']))
                $column_names[] = $column['label'];
            else
                $column_names[] = $column['name'];
        }

        $aData['issuperadmin'] = Permission::model()->hasGlobalPermission('superadmin');
        $aData['surveyid']= $iSurveyId;
        $aData['column_model_txt']= $column_model_txt;
        $aData['column_names_txt']= ls_json_encode($column_names);;
        $aData['hasUpload']=hasFileUploadQuestion($iSurveyId);


        $this->_renderWrappedTemplate('responses', 'listResponses_view', $aData);

    }

    
   /**
    * Returns survey responses in json format for a given survey
    *
    * @access public
    * @param $iSurveyID : survey id
    * @return json
    */
    public function getResponses_json($iSurveyID)
    {
        if(!Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
        {
            Yii::app()->end();
        }
        $aData = $this->_getData($iSurveyID);
        $bHaveToken=$aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read');
        extract($aData);
        $aViewUrls = array();
        $sBrowseLanguage = $aData['language'];
        $sImageURL     = Yii::app()->getConfig('adminimageurl');

        $fnames = array();
        $aSpecificColumns=array(
            'submitdate', // Replaced by completed : TODO : add it if is a real date
            'token', // Replaced by tokens.token
            'id', // Allways adding it at start
            'lastpage',
        );
        $aFieldmap = createFieldMap($iSurveyID, 'full', true, false, $aData['language']);

        // Get the survey responses

        $sOrder=Yii::app()->request->getPost('sord') == 'desc' ? 'desc' : 'asc';
        $sOrderBy=Yii::app()->request->getPost('sidx','id');
        $iPage=Yii::app()->request->getPost('page',1);
        $iLimit=Yii::app()->request->getPost('rows',50); // Default to 50 ?
        // Old behaviour : ajax default request from jqgrid need sort / rows (limit) / page (start) / sidx for order by : use javacript log please ....
        $oCriteria = new CDbCriteria;
        //Create the query
        if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
        {
            $oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
            $aSpecificColumns=array_merge($aSpecificColumns,TokenDynamic::model($iSurveyID)->getTableSchema()->getColumnNames());
        }

        if (incompleteAnsFilterState() == "incomplete")
        {
            $oCriteria->addCondition("submitdate IS NULL");
        }
        elseif (incompleteAnsFilterState() == "complete")
        {
            $oCriteria->addCondition("submitdate IS NOT NULL");
        }
        //Get the filter data
        //if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL")
        //    $oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));

        $aKnowColumns=array_keys(SurveyDynamic::model($iSurveyID)->attributes);
        if($bHaveToken){
            $aKnowColumns[]='firstname';
            $aKnowColumns[]='lastname';
            $aKnowColumns[]='email';
        }
        switch ($sOrderBy)
        {
            case 'completed':
                $sOrderBy='submitdate';
                break;
            default:
                if(!in_array($sOrderBy,$aKnowColumns))
                {
                    Yii::trace("unknow column $sOrderBy in json request");
                    $sOrderBy='id';
                }
        }
        $sOrderBy = Yii::app()->db->quoteColumnName($sOrderBy); // Maybe need to fix if $sOrderBy is in columns name
        $oCriteria->order = "{$sOrderBy} {$sOrder}";
        if(Yii::app()->request->getParam('_search'))
        {
            if(($value=Yii::app()->request->getParam('completed')) && !incompleteAnsFilterState()) //
            {
                if($value=='Y')
                    $oCriteria->addCondition("submitdate IS NOT NULL");
                elseif($value=='N')
                    $oCriteria->addCondition("submitdate IS NULL");
            }
            foreach($aKnowColumns as $sFiltering)
            {
                if($value=Yii::app()->request->getParam($sFiltering))
                {
                    if($sFiltering=='token')
                        $sFiltering='tokens.token';
                    $oCriteria->compare(Yii::app()->db->quoteColumnName($sFiltering),$value,true);
                }
            }
            if($sFilters=Yii::app()->request->getParam('filters'))
            {
                $aFilters=json_decode($sFilters);
                // TODO : groupOp and rules
            }

        }
        // Elements for nav bar of jquery
        $iCount = SurveyDynamic::model($iSurveyID)->count($oCriteria);// or die("Couldn't get response data<br />");
        $iLimit=((int)$iLimit>0) ?(int)$iLimit : 50 ;
        if (!$iLimit || $iLimit > $iCount)
        {
            $iLimit = $iCount;
        }
        $iStart=((int)$iPage>0) ? ((int)$iPage*$iLimit - $iLimit) : 0;
        $aSurveyEntries = new stdClass();
        $aSurveyEntries->page = $iPage; // Did we need to fix page ?
        $aSurveyEntries->total = ($iCount>0)?ceil($iCount/$iLimit):0;
        $aSurveyEntries->records= $iCount;

        // Last criteria update
        $oCriteria->offset = $iStart;
        $oCriteria->limit = $iLimit;

        // Get the rows
        $dtresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
        $all_rows = array();
        foreach ($dtresult as $row) {
            $action_html  = "<a href='" . Yii::app()->createUrl("admin/responses/view/surveyid/$surveyid/id/{$row['id']}") . "'><img src='" . $sImageURL . "token_viewanswer.png' alt='" . gT('View response details') . "'/></a>";
            if (Permission::model()->hasSurveyPermission($iSurveyID,'responses','update')) {
                $action_html .= "<a href='" . Yii::app()->createUrl("admin/dataentry/editdata/subaction/edit/surveyid/{$surveyid}/id/{$row['id']}") . "'><img src='" . $sImageURL . "edit_16.png' alt='" . gT('Edit this response') . "'/></a>";
            }
            if (hasFileUploadQuestion($surveyid)) {
                if(Response::model($surveyid)->findByPk($row['id'])->getFiles())
                    $action_html .= CHtml::link(
                        CHtml::image("{$sImageURL}down.png",gT('Download all files in this response as a zip file'),array("class"=>"downloadfile")),
                        Yii::app()->createUrl("admin/responses",array("sa"=>"actionDownloadfiles","surveyid"=>$surveyid,"sResponseId"=>$row['id']))
                    );
            }
            if (Permission::model()->hasSurveyPermission($iSurveyID,'responses','delete')) {
                $action_html .= "<a href='".Yii::app()->createUrl("admin/responses",array("sa"=>"actionDelete","surveyid"=>$surveyid,"sResponseId"=>$row['id']))."' data-delete='".$row['id']."'><img src='" . $sImageURL . "token_delete.png' alt='" . sprintf(gT('Delete response %s'),$row['id']) . "' class='deleteresponse'/></a>";
            }

            $aSurveyEntry = array();

            $aSurveyEntry[] = $action_html;

            $aSurveyEntry[] = $row['id'];
            $aSurveyEntry[] = $row['lastpage'];
            // completed
            $aSurveyEntry[] = empty($row['submitdate'])?'N':'Y';

            if ($bHaveToken)
            {
                if(is_null($row['tid']))
                    $aSurveyEntry[] = strip_tags($row['token']);
                else
                    $aSurveyEntry[] = "<a href='".Yii::app()->createUrl("admin/tokens",array("sa"=>"edit","surveyid"=>$surveyid,"tokenid"=>$row['tid']))."'>".strip_tags($row['token'])."</a>";

                $aSurveyEntry[] = strip_tags($row['firstname']);
                $aSurveyEntry[] = strip_tags($row['lastname']);
                $aSurveyEntry[] = strip_tags($row['email']);
            }


            // startlanguage
            //$aSurveyEntry[] = $row['startlanguage'];
            foreach ($row as $aFieldName => $mFieldValue) {

                if(in_array($aFieldName,$aSpecificColumns))
                    continue;
                $sSurveyEntry=strip_tags(getExtendedAnswer($iSurveyID, $aFieldName, $mFieldValue, $sBrowseLanguage)); // This fix XSS and get the value
                if($aFieldmap[$aFieldName]['type']=='|' && strpos($aFieldName,'filecount')===false)
                {
                    $aQuestionAttributes = getQuestionAttributeValues($aFieldmap[$aFieldName]['qid']);
                    $aFilesInfo = json_decode_ls($mFieldValue);
                    for ($iFileIndex = 0; $iFileIndex < $aQuestionAttributes['max_num_of_files']; $iFileIndex++)
                    {
                        if (isset($aFilesInfo[$iFileIndex]))
                        {
                            $aSurveyEntry[] = htmlspecialchars($aFilesInfo[$iFileIndex]['title'],ENT_QUOTES, 'UTF-8');
                            $aSurveyEntry[] = htmlspecialchars($aFilesInfo[$iFileIndex]['comment'],ENT_QUOTES, 'UTF-8');
                            $aSurveyEntry[] = CHtml::link(rawurldecode($aFilesInfo[$iFileIndex]['name']), $this->getController()->createUrl("/admin/responses",array("sa"=>"actionDownloadfile","surveyid"=>$surveyid,"iResponseId"=>$row['id'],"sFileName"=>$aFilesInfo[$iFileIndex]['name'])) );
                            $aSurveyEntry[] = sprintf('%s Mb',round($aFilesInfo[$iFileIndex]['size']/1000,2));
                        }
                        else
                        {
                            $aSurveyEntry[] = "";
                            $aSurveyEntry[] = "";
                            $aSurveyEntry[] = "";
                            $aSurveyEntry[] = "";
                        }

                    }
                }
                else
                {
                    $aSurveyEntry[] = $sSurveyEntry;
                }
            }
            $all_rows[] = array('id' => $row['id'], 'cell' =>  $aSurveyEntry);
        }

        $aSurveyEntries->rows = $all_rows;
        viewHelper::disableHtmlLogging();// It's better with but we need to fix error actually
        header('Content-type: application/json');
        echo json_encode($aSurveyEntries);
        Yii::app()->end();
    }
   
    
    /**
    * Saves the hidden columns for response browsing in the session
    *
    * @access public
    * @param $iSurveyID : survey id
    */

    public function setHiddenColumns($iSurveyId)
    {
        if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
        {
           $aHiddenFields=explode('|',Yii::app()->request->getPost('aHiddenFields')); 
           $_SESSION['survey_'.$iSurveyId]['HiddenFields']=$aHiddenFields;
        }
    }
    
    
    /**
    * Do an actions on response
    *
    * @access public
    * @param $iSurveyId : survey id
    * @return void
    */
    public function actionResponses($iSurveyId)
    {
        $action=Yii::app()->request->getPost('oper');
        $sResponseId=Yii::app()->request->getPost('id');
        switch ($action)
        {
            case 'downloadzip':
                $this->actionDownloadfiles($iSurveyId,$sResponseId);
                break;
            case 'del':
                $this->actionDelete($iSurveyId,$sResponseId);
                break;
            default:
                break;
        }
    }

    /**
    * Delete response
    * Allow to delete directly : leave it ? Can take $sResponseId by POST
    * @access public
    * @param $iSurveyId : survey id
    * @param $sResponseId : list of response
    * @return void
    */
    public function actionDelete($iSurveyId,$sResponseId)
    {
        if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','delete'))
        {
            $oSurvey=Survey::model()->findByPk($iSurveyId);
            //SurveyDynamic::model($iSurveyId)->deleteByPk($sResponseId);
            Response::model($iSurveyId)->findByPk($sResponseId)->delete(true);
            if($oSurvey->savetimings == "Y"){// TODO : add it to response delete (maybe test if timing table exist)
                SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
            }
        }
    }

    /**
    * Download individual file by response and filename
    *
    * @access public
    * @param $iSurveyId : survey id
    * @param $iResponseId : response if
    * @param $sFileName : The filename
    * @return application/octet-stream
    */
    public function actionDownloadfile($iSurveyId,$iResponseId,$sFileName)
    {
        if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
        {
            $oResponse = Response::model($iSurveyId)->findByPk($iResponseId);
            foreach ($oResponse->getFiles() as $aFile)
            {
                if (rawurldecode($aFile['name']) == rawurldecode($sFileName))
                {
                    $sFileRealName = Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyId . "/files/" . $aFile['filename'];
                    if (file_exists($sFileRealName))
                    {
                        @ob_clean();
                        header('Content-Description: File Transfer');
                        header('Content-Type: application/octet-stream');// Find the real type ?
                        header('Content-Disposition: attachment; filename="' . rawurldecode($aFile['name']) . '"');
                        header('Content-Transfer-Encoding: binary');
                        header('Expires: 0');
                        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                        header('Pragma: public');
                        header('Content-Length: ' . filesize($sFileRealName));
                        readfile($sFileRealName);
                        exit;
                    }
                    break;
                }
            }
            Yii::app()->setFlashMessage(gT("Sorry, this file was not found."),'error');
            $this->getController()->redirect(array("admin/responses","sa"=>"browse","surveyid"=>$surveyid));
        }
        
    }

    /**
    * Construct a zip files from a list of response
    *
    * @access public
    * @param $iSurveyId : survey id
    * @param $sResponseId : list of response
    * @return application/zip
    */
    public function actionDownloadfiles($iSurveyId,$sResponseId)
    {
        if(Permission::model()->hasSurveyPermission($iSurveyId,'responses','read'))
        {
            if(!$sResponseId) // No response id : get all survey files
            {
                $oCriteria = new CDbCriteria();
                $oCriteria->select = "id";
                $oSurvey = SurveyDynamic::model($iSurveyId);
                $aResponseId = $oSurvey->getCommandBuilder()
                ->createFindCommand($oSurvey->tableSchema, $oCriteria)
                ->queryColumn();
            }
            else
            {
                $aResponseId=explode(",",$sResponseId);
            }
            if(!empty($aResponseId))
            {
                // Now, zip all the files in the filelist
                if(count($aResponseId)==1)
                    $zipfilename = "Files_for_survey_{$iSurveyId}_response_{$aResponseId[0]}.zip";
                else
                    $zipfilename = "Files_for_survey_{$iSurveyId}.zip";

                $this->_zipFiles($iSurveyId, $aResponseId, $zipfilename);
            }
            else
            {
                // No response : redirect to browse with a alert
                Yii::app()->setFlashMessage(gT("The requested files do not exist on the server."),'error');
                $this->getController()->redirect(array("admin/responses","sa"=>"browse","surveyid"=>$surveyid));
            }
        }
    }
    /**
    * @deprecated
    * */
    function oldbrowse($iSurveyID)
    {
        $aData = $this->_getData($iSurveyID);
        extract($aData);
        $aViewUrls = array();
        $sBrowseLanguage = $aData['language'];
        $tokenRequest = Yii::app()->request->getParam('token', null);


        /**
        * fnames is used as informational array
        * it containts
        *             $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
        */
        if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
        {
            if (Yii::app()->request->getPost('sql'))
            {
                $aViewUrls[] = 'browseallfiltered_view';
            }
            //add token to top of list if survey is not private
            if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) ) //add token to top of list if survey is not private
            {
                if(Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
                {
                    $fnames[] = array("token", gT("Token ID"), 'code'=>'token');
                    $fnames[] = array("firstname", gT("First name"), 'code'=>'firstname');// or token:firstname ?
                    $fnames[] = array("lastname", gT("Last name"), 'code'=>'lastname');
                    $fnames[] = array("email", gT("Email"), 'code'=>'email');
                }
            }

            $fnames[] = array("submitdate", gT("Completed"), gT("Completed"), "0", 'D');
            $fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);

            foreach ($fields as $fielddetails)
            {
                if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate')
                    continue;

                $question = $fielddetails['question'];
                if ($fielddetails['type'] != "|")
                {
                    if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token')
                        continue;

                    // no headers for time data
                    if ($fielddetails['type'] == 'interview_time')
                        continue;
                    if ($fielddetails['type'] == 'page_time')
                        continue;
                    if ($fielddetails['type'] == 'answer_time')
                        continue;
                    $fnames[] = array($fielddetails['fieldname'], viewHelper::getFieldText($fielddetails),'code'=>viewHelper::getFieldCode($fielddetails,array('LEMcompat'=>true)));
                }
                elseif ($fielddetails['aid'] !== 'filecount')
                {
                    $qidattributes = getQuestionAttributeValues($fielddetails['qid']);
                    for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
                    {
                        $filenum=sprintf(gT("File %s"),$i + 1);
                        if ($qidattributes['show_title'] == 1)
                            $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".gT('Title').")",'code'=>viewHelper::getFieldCode($fielddetails).'(title)', "type" => "|", "metadata" => "title", "index" => $i);
                        if ($qidattributes['show_comment'] == 1)
                            $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".gT('Comment').")",'code'=>viewHelper::getFieldCode($fielddetails).'(comment)', "type" => "|", "metadata" => "comment", "index" => $i);

                        $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".gT('File name').")",'code'=>viewHelper::getFieldCode($fielddetails).'(name)', "type" => "|", "metadata" => "name", "index" => $i);
                        $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".gT('File size').")",'code'=>viewHelper::getFieldCode($fielddetails).'(size)', "type" => "|", "metadata" => "size", "index" => $i);

                        //$fnames[] = array($fielddetails['fieldname'], "File ".($i+1)." - ".$fielddetails['question']."(extension)", "type"=>"|", "metadata"=>"ext",     "index"=>$i);
                    }
                }
                else
                {
                    $fnames[] = array($fielddetails['fieldname'], gT("File count"), 'code'=>viewHelper::getFieldCode($fielddetails));
                }
            }

            $fncount = count($fnames);

            $start = (int)Yii::app()->request->getParam('start', 0);
            $limit = (int)Yii::app()->request->getParam('limit', 50);
            $order =  Yii::app()->request->getParam('order', 'asc');
            if(!$limit){$limit=50;}
            $oCriteria = new CDbCriteria;
            //Create the query
            if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
            {
                $oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
            }

            if (incompleteAnsFilterState() == "incomplete")
            {
                $oCriteria->addCondition("submitdate IS NULL");
            }
            elseif (incompleteAnsFilterState() == "complete")
            {
                $oCriteria->addCondition("submitdate IS NOT NULL");
            }

            $dtcount = SurveyDynamic::model($iSurveyID)->count($oCriteria);// or die("Couldn't get response data<br />");

            if ($limit > $dtcount)
            {
                $limit = $dtcount;
            }

            //NOW LETS SHOW THE DATA
            if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL")
                $oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));

            if (!is_null($tokenRequest)) {
                $oCriteria->addCondition('t.token = ' . Yii::app()->db->quoteValue($tokenRequest));
            }

            $oCriteria->order = 'id ' . ($order == 'desc' ? 'desc' : 'asc');
            $oCriteria->offset = $start;
            $oCriteria->limit = $limit;

            $dtresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);

            $dtcount2 = count($dtresult);
            $cells = $fncount + 1;
            // Fix start if order is desc, only if actual start is 0
            if($order == 'desc' && $start==0)
            {
                $start=$dtcount-count($dtresult);
            }

            //CONTROL MENUBAR
            $last = $start - $limit;
            $next = $start + $limit;
            $end = $dtcount - $limit;
            if ($end < 0)
            {
                $end = 0;
            }
            if ($last < 0)
            {
                $last = 0;
            }
            if ($next >= $dtcount)
            {
                $next = $dtcount - $limit;
            }
            if ($end < 0)
            {
                $end = 0;
            }

            $aData['dtcount2'] = $dtcount2;
            $aData['sCompletionStateValue']=incompleteAnsFilterState();

            $aData['start'] = $start;
            $aData['limit'] = $limit;
            $aData['last'] = $last;
            $aData['next'] = $next;
            $aData['end'] = $end;
            $aData['fncount'] = $fncount;
            $aData['fnames'] = $fnames;
            $aData['bHasFileUploadQuestion'] = hasFileUploadQuestion($iSurveyID);

            $aViewUrls[] = 'browseallheader_view';

            $bgcc = 'even';
            foreach ($dtresult as $dtrow)
            {
                if ($bgcc == "even")
                {
                    $bgcc = "odd";
                }
                else
                {
                    $bgcc = "even";
                }
                $aData['dtrow'] = $dtrow;
                $aData['bgcc'] = $bgcc;
                $aData['sBrowseLanguage']=$sBrowseLanguage;
                $aViewUrls['browseallrow_view'][] = $aData;
            }

            $aViewUrls[] = 'browseallfooter_view';
            $this->_renderWrappedTemplate('',$aViewUrls, $aData);
        }
        else
        {
            $aData['surveyid'] = $iSurveyID;
            App()->getClientScript()->registerPackage('jquery-superfish');
            $message['title']= gT('Access denied!');
            $message['message']= gT('You do not have sufficient rights to access this page.');
            $message['class']= "error";
            $this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
        }
    }

    public function time($iSurveyID)
    {
        $aData = $this->_getData(array('iSurveyId' => $iSurveyID));
        extract($aData);
        $aViewUrls = array();

        if ($aData['surveyinfo']['savetimings'] != "Y")
            die();

        if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked'
        && Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete'))
        {
            $iResponseID=(int) Yii::app()->request->getPost('deleteanswer');
            SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
            SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
        }

        if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0)
        {
            if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked' &&
            Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete'))
            {
                foreach (Yii::app()->request->getPost('markedresponses') as $iResponseID)
                {
                    $iResponseID=(int) $iResponseID;
                    SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
                    SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
                }
            }
        }

        $fields = createTimingsFieldMap($iSurveyID, 'full',true,false,$aData['language']);

        foreach ($fields as $fielddetails)
        {
            // headers for answer id and time data
            if ($fielddetails['type'] == 'id')
                $fnames[] = array($fielddetails['fieldname'], $fielddetails['question']);
            if ($fielddetails['type'] == 'interview_time')
                $fnames[] = array($fielddetails['fieldname'], gT('Total time'));
            if ($fielddetails['type'] == 'page_time')
                $fnames[] = array($fielddetails['fieldname'], gT('Group') . ": " . $fielddetails['group_name']);
            if ($fielddetails['type'] == 'answer_time')
                $fnames[] = array($fielddetails['fieldname'], gT('Question') . ": " . $fielddetails['title']);
        }
        $fncount = count($fnames);

        //NOW LETS CREATE A TABLE WITH THOSE HEADINGS
        foreach ($fnames as $fn)
        {
            if (!isset($currentgroup))
            {
                $currentgroup = $fn[1];
                $gbc = "oddrow";
            }
            if ($currentgroup != $fn[1])
            {
                $currentgroup = $fn[1];
                if ($gbc == "oddrow")
                {
                    $gbc = "evenrow";
                }
                else
                {
                    $gbc = "oddrow";
                }
            }
        }
        $aData['fnames'] = $fnames;
        $start = Yii::app()->request->getParam('start', 0);
        $limit = Yii::app()->request->getParam('limit', 50);
        if(!$limit){$limit=50;}
        //LETS COUNT THE DATA
        $oCriteria = new CdbCriteria();
        $oCriteria->select = 'tid';
        $oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
        $oCriteria->condition = 'submitdate IS NOT NULL';
        $dtcount = SurveyTimingDynamic::model($iSurveyID)->count($oCriteria); // or die("Couldn't get response data");

        if ($limit > $dtcount)
        {
            $limit = $dtcount;
        }

        //NOW LETS SHOW THE DATA
        $oCriteria = new CdbCriteria();
        $oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
        $oCriteria->condition = 'submitdate IS NOT NULL';
        $oCriteria->order = "s.id " . (Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc');
        $oCriteria->offset = $start;
        $oCriteria->limit = $limit;

        $dtresult = SurveyTimingDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
        $dtcount2 = count($dtresult);
        $cells = $fncount + 1;

        //CONTROL MENUBAR
        $last = $start - $limit;
        $next = $start + $limit;
        $end = $dtcount - $limit;
        if ($end < 0)
        {
            $end = 0;
        }
        if ($last < 0)
        {
            $last = 0;
        }
        if ($next >= $dtcount)
        {
            $next = $dtcount - $limit;
        }
        if ($end < 0)
        {
            $end = 0;
        }

        $aData['sCompletionStateValue']=incompleteAnsFilterState();
        $aData['start'] = $start;
        $aData['limit'] = $limit;
        $aData['last'] = $last;
        $aData['next'] = $next;
        $aData['end'] = $end;
        $aViewUrls[] = 'browsetimeheader_view';

        $aData['fncount'] = $fncount;
        $bgcc = 'oddrow';

        foreach ($dtresult as $dtrow)
        {
            if ($bgcc == "evenrow")
            {
                $bgcc = "oddrow";
            }
            else
            {
                $bgcc = "evenrow";
            }
            $browsedatafield=array();
            for ($i = 0; $i < $fncount; $i++)
            {
                $browsedatafield[$i] = $dtrow[$fnames[$i][0]];
                // seconds -> minutes & seconds
                if (strtolower(substr($fnames[$i][0], -4)) == "time")
                {
                    $minutes = (int) ($browsedatafield[$i] / 60);
                    $seconds = $browsedatafield[$i] % 60;
                    $browsedatafield[$i] = '';
                    if ($minutes > 0)
                        $browsedatafield[$i] .= "$minutes min ";
                    $browsedatafield[$i] .= "$seconds s";
                }
            }
            $aData['browsedatafield'] = $browsedatafield;
            $aData['bgcc'] = $bgcc;
            $aData['dtrow'] = $dtrow;
            $aViewUrls['browsetimerow_view'][] = $aData;
        }

        //interview Time statistics
        $aData['statistics'] = SurveyTimingDynamic::model($iSurveyId)->statistics();
        $aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
        $aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
        $aViewUrls[] = 'browsetimefooter_view';
        $this->_renderWrappedTemplate('',$aViewUrls, $aData);
    }

    /**
    * Supply an array with the responseIds and all files will be added to the zip
    * and it will be be spit out on success
    *
    * @param array $responseIds
    * @param string $zipfilename
    * @param string $language
    * @return ZipArchive
    */
    private function _zipFiles($iSurveyID, $responseIds, $zipfilename)
    {
        /**
        * @todo Move this to model.
        */
        Yii::app()->loadLibrary('admin/pclzip');

        $tmpdir = Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR."surveys". DIRECTORY_SEPARATOR . $iSurveyID . DIRECTORY_SEPARATOR."files".DIRECTORY_SEPARATOR;

        $filelist = array();
        $responses = Response::model($iSurveyID)->findAllByPk($responseIds);
        $filecount = 0;
        foreach ($responses as $response)
        {
            foreach ($response->getFiles() as $file)
            {
                $filecount++;
                /*
                * Now add the file to the archive, prefix files with responseid_index to keep them
                * unique. This way we can have 234_1_image1.gif, 234_2_image1.gif as it could be
                * files from a different source with the same name.
                */
                if (file_exists($tmpdir . basename($file['filename'])))
                {
                    $filelist[] = array(PCLZIP_ATT_FILE_NAME => $tmpdir . basename($file['filename']),
                        PCLZIP_ATT_FILE_NEW_FULL_NAME => sprintf("%05s_%02s_%s", $response->id, $filecount, rawurldecode($file['name'])));
                }
            }
        }

        if (count($filelist) > 0)
        {
            $zip = new PclZip($tmpdir . $zipfilename);
            if ($zip->create($filelist) === 0)
            {
                //Oops something has gone wrong!
            }

            if (file_exists($tmpdir . '/' . $zipfilename))
            {
                @ob_clean();
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . basename($zipfilename));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($tmpdir . "/" . $zipfilename));
                readfile($tmpdir . '/' . $zipfilename);
                unlink($tmpdir . '/' . $zipfilename);
                exit;
            }
        }
        // No files : redirect to browse with a alert
        Yii::app()->setFlashMessage(gT("Sorry, there are no files for this response."),'error');
        $this->getController()->redirect(array("admin/responses","sa"=>"browse","surveyid"=>$iSurveyID));
    }

    /**
    * Renders template(s) wrapped in header and footer
    *
    * @param string|array $aViewUrls View url(s)
    * @param array $aData Data to be passed on. Optional.
    */
    protected function _renderWrappedTemplate($sAction='', $aViewUrls = array(), $aData = array())
    {
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'browse.js');

        $aData['display']['menu_bars'] = false;
        $aData['display']['menu_bars']['browse'] = gT('Browse responses'); // browse is independent of the above

        parent::_renderWrappedTemplate('responses', $aViewUrls, $aData);
    }

}
